<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/blog/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"always","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="（NOHUP, SETSID, &amp;, DISOWN）Linux 将进程放入后台执行，解决网络，ssh断开导致进程结束（nohup,  setsid,  &amp;, disown） 1、nohup 命令 我们知道，当用户注销（logout）或者网络断开时，终端会收到 HUP（hangup）信号从而关闭其所有子进程。因此，我们的解决办法就有两种途径：要么让进程忽略 HUP 信号，要么让进程运">
<meta property="og:type" content="article">
<meta property="og:title" content="LINUX 将进程放入后台执行，SSH 断开导致进程结束">
<meta property="og:url" content="http://example.com/2021/09/29/nohup/index.html">
<meta property="og:site_name" content="ingrun">
<meta property="og:description" content="（NOHUP, SETSID, &amp;, DISOWN）Linux 将进程放入后台执行，解决网络，ssh断开导致进程结束（nohup,  setsid,  &amp;, disown） 1、nohup 命令 我们知道，当用户注销（logout）或者网络断开时，终端会收到 HUP（hangup）信号从而关闭其所有子进程。因此，我们的解决办法就有两种途径：要么让进程忽略 HUP 信号，要么让进程运">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-29T03:40:46.413Z">
<meta property="article:modified_time" content="2021-10-19T02:00:20.616Z">
<meta property="article:author" content="ingrun">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/09/29/nohup/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>LINUX 将进程放入后台执行，SSH 断开导致进程结束 | ingrun</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">ingrun</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">不吃花生</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/29/nohup/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="ingrun">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ingrun">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LINUX 将进程放入后台执行，SSH 断开导致进程结束
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-09-29 11:40:46" itemprop="dateCreated datePublished" datetime="2021-09-29T11:40:46+08:00">2021-09-29</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-19 10:00:20" itemprop="dateModified" datetime="2021-10-19T10:00:20+08:00">2021-10-19</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="（NOHUP-SETSID-amp-DISOWN）"><a href="#（NOHUP-SETSID-amp-DISOWN）" class="headerlink" title="（NOHUP, SETSID, &amp;, DISOWN）"></a>（NOHUP, SETSID, &amp;, DISOWN）</h2><p>Linux 将进程放入后台执行，解决网络，ssh断开导致进程结束（nohup,  setsid,  &amp;, disown）</p>
<p>1、nohup 命令</p>
<p>我们知道，当用户注销（logout）或者网络断开时，终端会收到 HUP（hangup）信号从而关闭其所有子进程。因此，我们的解决办法就有两种途径：要么让进程忽略 HUP 信号，要么让进程运行在新的会话里从而成为不属于此终端的子进程</p>
<p>nohup &amp; 命令并不能从根本上解决ssh断开问题。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1 [root@Searchsvc1 go-mysql-elasticsearch]# nohup tail -f nohup.out &amp;</span><br><span class="line">2 [1] 21509</span><br></pre></td></tr></table></figure>
<p>pid所属的父id为：21476</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1 [root@Searchsvc1 go-mysql-elasticsearch]# ps -ef |grep tail</span><br><span class="line">2 root     21509 21476 98 21:39 pts&#x2F;1    00:01:17 tail -f nohup.out</span><br><span class="line">3 root     21518 20971  0 21:40 pts&#x2F;0    00:00:00 grep tail</span><br></pre></td></tr></table></figure>
<p>通过 pstree  -p 查看线程树可知它属于ssh的一个子线程，所以关闭ssh的时候，会将其子线程hangup。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1   ├─sshd(1472)─┬─sshd(20967)───bash(20971)───pstree(21516)</span><br><span class="line">2         │            └─sshd(21472)───bash(21476)───tail(21509)</span><br></pre></td></tr></table></figure>


<p>2、 setsid 命令</p>
<p>我们换个角度思考，如果我们的进程不属于接受 HUP 信号的终端的子进程，那么自然也就不会受到 HUP 信号的影响了。setsid 就能帮助我们做到这一点。让我们先来看一下 setsid 的帮助信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1 [root@Searchsvc1 go-mysql-elasticsearch]# setsid tail -f nohup.out </span><br><span class="line">2 [root@Searchsvc1 go-mysql-elasticsearch]# 2017&#x2F;11&#x2F;16 21:34:30 master.go:54: [info] save position (mysql-bin.000052, 98963482)</span><br><span class="line">3 2017&#x2F;11&#x2F;16 21:35:13 master.go:54: [info] save position (mysql-bin.000052, 98966359)</span><br><span class="line">setsid 命令会将结果信息输出到控制台，并没有从真正意义上将线程转向后台执行</span><br><span class="line">我们再来看下执行该命令后的进程的父pid:1 ,已经跟ssh已经没有关系了。</span><br></pre></td></tr></table></figure>


<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1 init(1)─┬─abrtd(1572)</span><br><span class="line">2         ├─acpid(1363)</span><br><span class="line">3         ├─atd(1609)</span><br><span class="line">4     </span><br><span class="line">5         ├─sshd(1472)─┬─sshd(20967)───bash(20971)───pstree(21650)</span><br><span class="line">6         │            └─sshd(21472)───bash(21476)</span><br><span class="line">7         ├─tail(21645)</span><br></pre></td></tr></table></figure>


<p>这里还有一个关于 subshell 的小技巧。我们知道，将一个或多个命名包含在“()”中就能让这些命令在子 shell 中运行中，从而扩展出很多有趣的功能，我们现在要讨论的就是其中之一。当我们将”&amp;”也放入“()”内之后，我们就会发现所提交的作业并不在作业列表中，也就是说，是无法通过<code>jobs</code>来查看的。让我们来看看为什么这样就能躲过 HUP 信号的影响吧。</p>
<p>但用&amp;能将进程转向后台，但是</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1 ├─sshd(1472)─┬─sshd(20967)───bash(20971)───pstree(21662)</span><br><span class="line">2         │            └─sshd(21472)───bash(21476)───tail(21655)</span><br></pre></td></tr></table></figure>
<p>（）命令</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">1 [root@Searchsvc1 go-mysql-elasticsearch]# (tail -f nohup.out)</span><br><span class="line">2 2017&#x2F;11&#x2F;16 21:57:38 master.go:54: [info] save position (mysql-bin.000052, 99185120)</span><br><span class="line">1  ├─sshd(1472)─┬─sshd(20967)───bash(20971)───pstree(21664)</span><br><span class="line">2         │            └─sshd(21472)───bash(21476)───tail(21663)</span><br></pre></td></tr></table></figure>
<p>从上面可以看出&amp;,()都会将结果信息输出到控制台，而且转向后台的线程会因为ssh的关闭而影响，但是执行（tail -f nohup.out &amp;）却能改变结果，进程将不再属于ssh的子进程</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1         ├─sshd(1472)─┬─sshd(20967)───bash(20971)───pstree(21685)</span><br><span class="line">2         │            └─sshd(21472)───bash(21476)</span><br><span class="line">3         ├─tail(21683)</span><br></pre></td></tr></table></figure>


<p>4、disown命令</p>
<p>我们已经知道，如果事先在命令前加上 nohup 或者 setsid 就可以避免 HUP 信号的影响。但是如果我们未加任何处理就已经提交了命令，该如何补救才能让它避免 HUP 信号的影响呢？</p>
<ul>
<li>用<code>disown -h *jobspec*</code>来使某个作业忽略HUP信号。</li>
<li>用<code>disown -ah </code>来使所有的作业都忽略HUP信号。</li>
<li>用<code>disown -rh </code>来使正在运行的作业忽略HUP信号。</li>
</ul>
<p>需要注意的是，当使用过 disown 之后，会将把目标作业从作业列表中移除，我们将不能再使用<code>jobs</code>来查看它，但是依然能够用<code>ps -ef</code>查找到它。</p>
<p>5、screen 命令</p>
<ul>
<li>用<code>screen -dmS *session name*</code>来建立一个处于断开模式下的会话（并指定其会话名）。</li>
<li>用<code>screen -list </code>来列出所有会话。</li>
<li>用<code>screen -r *session name*</code>来重新连接指定会话。</li>
<li>用快捷键<code>CTRL-a d </code>来暂时断开当前会话。</li>
</ul>
<p>6、PS命令</p>
<p>在ps命令中，“-T”选项可以开启线程查看。下面的命令列出了由进程号为<pid>的进程创建的所有线程。</p>
<p> ps -T -p <pid></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1 [root@Searchsvc1 go-mysql-elasticsearch]# ps -T -p 21813</span><br><span class="line">2   PID  SPID TTY          TIME CMD</span><br></pre></td></tr></table></figure>


<p>“SID”栏表示线程ID，而“CMD”栏则显示了线程名称。</p>
<p>7、 Top命令</p>
<p>top命令可以实时显示各个线程情况。要在top输出中开启线程查看，请调用top命令的“-H”选项，该选项会列出所有Linux线程。在top运行时，你也可以通过按“H”键将线程查看模式切换为开或关。</p>
<p>1、 top -H</p>
<p>2、要让top输出某个特定进程<pid>并检查该进程内运行的线程状况：top -H -p <pid>。</p>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/images/wx.png" alt="ingrun 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/images/zfb.jpg" alt="ingrun 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/08/16/sql%E4%BC%98%E5%8C%96/" rel="prev" title="SQL 优化">
      <i class="fa fa-chevron-left"></i> SQL 优化
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/05/05/JS%20%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C/" rel="next" title="JS 的一些常用操作">
      JS 的一些常用操作 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%EF%BC%88NOHUP-SETSID-amp-DISOWN%EF%BC%89"><span class="nav-number">1.</span> <span class="nav-text">（NOHUP, SETSID, &amp;, DISOWN）</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">ingrun</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">16</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ingrun</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
